package com.ywz.project.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ywz.common.ResultResp;
import com.ywz.common.StringUtils;
import com.ywz.project.base.system.entity.TSysOperLog;
import com.ywz.project.base.system.service.TSysOperLogService;
import com.ywz.project.system.dto.req.OperLogPageReq;
import com.ywz.project.system.service.OperLogApiService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class OperLogApiServiceImpl implements OperLogApiService {
    @Resource
    private TSysOperLogService tSysOperLogService;

    @Override
    public ResultResp getOperLogPage(OperLogPageReq req) {
        LambdaQueryWrapper<TSysOperLog> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(TSysOperLog::getIsDeleted, 0);
        if (!StringUtils.isEmpty(req.getUser()))
            queryWrapper.like(TSysOperLog::getOperName, req.getUser());
        if (StringUtils.isDate(req.getStartTime()))
            queryWrapper.ge(TSysOperLog::getCreatedTime, req.getStartTime());
        if (StringUtils.isDate(req.getEndTime()))
            queryWrapper.le(TSysOperLog::getCreatedTime, req.getEndTime());
        queryWrapper.orderByDesc(TSysOperLog::getCreatedTime);
        Page<TSysOperLog> page = new Page<>(req.getPageNum(), req.getPageSize());
        return ResultResp.success(tSysOperLogService.page(page, queryWrapper));
    }

    @Override
    public ResultResp removeOperLog(String ids) {
        if (StringUtils.isNumberAndSeparator(ids)) {
            String[] split = ids.split(StringUtils.SEPARATOR);
            List<Long> collect = Arrays.stream(split).map(Long::valueOf).collect(Collectors.toList());
            LambdaUpdateWrapper<TSysOperLog> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.in(TSysOperLog::getId, collect);
            updateWrapper.set(TSysOperLog::getIsDeleted, 1);
            updateWrapper.set(TSysOperLog::getUpdatedTime, LocalDateTime.now());
            boolean updated = tSysOperLogService.update(updateWrapper);
            return updated ? ResultResp.success("删除成功") : ResultResp.error("删除失败");
        } else {
            return ResultResp.error("参数错误");
        }
    }
}
